package com.kingyun.gpsinspection.purificationservice.services.jsm.innerservice.impl.employee;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.kingyun.gpsinspection.purificationservice.common.enums.TreeIconSkinEnum;
import com.kingyun.gpsinspection.purificationservice.common.utils.BootstrapUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.adm.EmployeeCertificateMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.DepartmentMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.EmployeeMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.JsmFileMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.OutZtreeService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.department.JsmDepartmentService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.employee.JsmCertificateTypeService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.employee.JsmEmployeeCertificateService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.employee.JsmEmployeeService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.file.JsmFileService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.organization.JsmOrganizationService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.post.JsmPostTypeService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.teaminfo.JsmTeamInfoService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.teaminfo.JsmTeamMembersService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by zmling on 2016/11/22.
 * 人员信息
 */
public class JsmEmployeeServiceImpl implements JsmEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private JsmCertificateTypeService jsmCertificateTypeService;
    @Autowired
    private JsmEmployeeCertificateService jsmEmployeeCertificateService;
    @Autowired
    private JsmFileService fileService;
    @Autowired
    private EmployeeCertificateMapper employeeCertificateMapper;
    @Autowired
    private JsmFileMapper fileMapper;
    @Autowired
    private JsmOrganizationService organizationService;
    @Autowired
    private JsmDepartmentService departmentService;
    @Autowired
    private JsmTeamInfoService teamInfoService;
    @Autowired
    private JsmTeamMembersService jsmTeamMembersService;
    @Autowired
    private JsmPostTypeService jsmPostTypeService;
    @Autowired
    private OutZtreeService outZtreeService;

    /**
     * 新增
     *
     * @param employee
     * @param employeeCertificate
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void employeeAdd(Employee employee, List<EmployeeCertificateVo> employeeCertificate, String uploadFiles, String deletedFiles, Employee e, String uploadSignature) throws Exception {
        if (employee != null) {
            String employeeId = UniqueUtil.uuid();
            employee.setEmployeeId(employeeId);
            employee.setCreatorId(e.getEmployeeId());
            employee.setModifierId(e.getEmployeeId());
            employee.setOperatorId(e.getEmployeeId());
            Date date = new Date();
            employee.setModifyTime(date);
            employee.setCreateTime(date);
            employee.setPassword(null != employee.getPassword() && !employee.getPassword().equals("") ? employee.getPassword() : "123456");
            //状态0是正常；1是删除
            employee.setStatus((short) 0);
            if (null != employee.getEnrollDatets() && !"".equals(employee.getEnrollDatets())) {
                employee.setEnrollDate(DateUtil.StringToDate(employee.getEnrollDatets(), DateStyle.YYYY_MM_DD));
            }
            if (null != employee.getBirthdayts() && !"".equals(employee.getBirthdayts())) {
                employee.setBirthday(DateUtil.StringToDate(employee.getBirthdayts(), DateStyle.YYYY_MM_DD));
            }
            //保存签名图
            saveSignature(uploadSignature, employee);
            employeeMapper.insertSelective(employee);
            //保存上传图像
            fileService.addFile(uploadFiles, deletedFiles, employeeId);
            //保存人员对应的证书信息
            if (employeeCertificate.size() > 0) {
                for (EmployeeCertificateVo emlcf : employeeCertificate) {
                    if (emlcf.getName() != null && emlcf.getName() != "") {
                        CertificateType certificateType = jsmCertificateTypeService.findCertificateType(emlcf.getName());
                        emlcf.setCertificateTypeId(certificateType.getCertificateTypeId());
                    }
                    emlcf.setEmployeeCertificateId(UniqueUtil.uuid());
                    emlcf.setEmployeeId(employeeId);
                    emlcf.setName(employee.getName());
                    emlcf.setCreateTime(new Date());
                    emlcf.setCreatorId(e.getEmployeeId());
                    emlcf.setModifierId(e.getEmployeeId());
                    emlcf.setModifyTime(new Date());
                    emlcf.setState(BigDecimal.valueOf(0));
                    jsmEmployeeCertificateService.addEmployeeCertificate(emlcf);
                    //保存证书信息对应的附件信息
                    if (emlcf.getUploadedFiles() != null) {
                        String uploadFiless = JSON.toJSONString(emlcf.getUploadedFiles());
                        fileService.addFile(uploadFiless, null, emlcf.getEmployeeCertificateId());
                    }
                }
            }
        }
    }

    /**
     * 将上传文件的hbase路径保存到字段中
     *
     * @param employee
     * @param uploadSignature
     */
    private void saveSignature(String uploadSignature, Employee employee) {
        if (!StringUtils.isEmpty(uploadSignature) && !uploadSignature.equals("[]")) {
            List<File> listFiles = JSON.parseArray(uploadSignature, File.class);
            for (File file : listFiles) {
                employee.setSignatureHBasePath(file.getFileHbasePath());
            }
        }
    }

    /**
     * 查询列表
     *
     * @param employee
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject findEmployeeList(Employee employee) throws Exception {
        JSONObject jsonObject = new JSONObject();
        if (null != employee.getEnrollDatets() && !"".equals(employee.getEnrollDatets())) {
            employee.setEnrollDate(DateUtil.StringToDate(employee.getEnrollDatets(), DateStyle.YYYY_MM_DD));
        }
        employee.setLimit(employee.getLimit() == null ? 10 : employee.getLimit());
        employee.setOffset(employee.getOffset() == null ? 0 : employee.getOffset());
        employee.setFilterMap(BootstrapUtil.filterStringToMap(employee.getFilter()));
        if (employee.getSearch() != null && employee.getSearch() != "") {
            employee.setSearch(employee.getSearch().trim());
        }
        jsonObject.put("total", employeeMapper.queryCount(employee));
        List<EmployeeVo> list = employeeMapper.queryList(employee);
        if (list.size() > 0) {
            for (EmployeeVo li : list) {
                if (li != null && li.getDepName() == null && li.getOrgName() != null) {
                    li.setDepName(li.getOrgName());
                }
            }
        }
        jsonObject.put("rows", JSON.toJSON(list));
        return jsonObject;
    }

    /**
     * 根据主键查询人员信息
     *
     * @param employeeId
     * @return
     * @throws Exception
     */
    @Override
    public EmployeeVo findEmployeeById(String employeeId) throws Exception {
        EmployeeVo employee = employeeMapper.selectByPrimaryKey(employeeId);
        if (employee != null && StringUtils.isNotEmpty(employee.getWorkSpeciesId())) {
            List<String> list = new ArrayList<String>(Arrays.asList(employee.getWorkSpeciesId().split(",")));
            PostType pt = new PostType();
            pt.setList(list);
            pt.setPostType((short) 2);
            List<PostType> ptList = jsmPostTypeService.selectByPostTypeId(pt);
            int i = 0;
            StringBuffer sb = new StringBuffer();
            for (PostType p : ptList) {
                if (i == 0) {
                    sb.append(p.getPosttypeName());
                    i = 1;
                } else {
                    sb.append("," + p.getPosttypeName());
                }
            }
            employee.setBirthdayts(sb.toString());
        }
        return employee;
    }

    /**
     * 修改
     *
     * @param employee
     * @param employeeCertificate
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void employeeUpdate(Employee employee, List<EmployeeCertificateVo> employeeCertificate, String uploadFiles, String deletedFiles, Employee e, String uploadSignature) throws Exception {
        if (employee != null) {
            employee.setModifyTime(new Date());
            if (employee.getEnrollDatets() != null && employee.getEnrollDatets() != "") {
                employee.setEnrollDate(DateUtil.StringToDate(employee.getEnrollDatets(), DateStyle.YYYY_MM_DD));
            }
            if (employee.getBirthdayts() != null && employee.getBirthdayts() != "") {
                employee.setBirthday(DateUtil.StringToDate(employee.getBirthdayts(), DateStyle.YYYY_MM_DD));
            }
            employee.setModifierId(e.getEmployeeId());
            employee.setModifyTime(new Date());
            employee.setPassword(null != employee.getPassword() && !employee.getPassword().equals("") ? employee.getPassword() : "123456");
            saveSignature(uploadSignature, employee);
            employeeMapper.updateByPrimaryKeySelective(employee);

            //保存上传图像
            fileService.addDelFile(uploadFiles, employee.getEmployeeId());
            if (null != employeeCertificate && employeeCertificate.size() > 0) {
                for (EmployeeCertificateVo emlcf : employeeCertificate) {
                    if (emlcf.getName() != null && emlcf.getName() != "") {
                        CertificateType certificateType = jsmCertificateTypeService.findCertificateType(emlcf.getName());
                        emlcf.setCertificateTypeId(certificateType.getCertificateTypeId());
                    }
                    if (emlcf.getEmployeeCertificateId() != null && emlcf.getEmployeeCertificateId() != "") {
                        emlcf.setCreatorId(e.getEmployeeId());
                        jsmEmployeeCertificateService.updateEmployeeCertificate(emlcf);
                    } else {
                        emlcf.setEmployeeCertificateId(UniqueUtil.uuid());
                        emlcf.setEmployeeId(employee.getEmployeeId());
                        emlcf.setName(employee.getName());
                        emlcf.setCreateTime(new Date());
                        emlcf.setCreatorId(e.getEmployeeId());
                        emlcf.setModifierId(e.getEmployeeId());
                        emlcf.setModifyTime(new Date());
                        emlcf.setState(BigDecimal.valueOf(0));
                        jsmEmployeeCertificateService.addEmployeeCertificate(emlcf);
                    }
                    //保存证书信息对应的附件信息
                    String uploadFiless = null;
                    String deletedFiless = null;
                    if (emlcf.getDeletedFiles() != null) {
                        deletedFiless = JSON.toJSONString(emlcf.getDeletedFiles());
                    }
                    if (emlcf.getUploadedFiles() != null) {
                        uploadFiless = JSON.toJSONString(emlcf.getUploadedFiles());
                    }
                    fileService.updateFile(uploadFiless, deletedFiless, emlcf.getEmployeeCertificateId());
                }
            }
        }
    }

    /**
     * 删除
     *
     * @param employee
     * @return
     * @throws Exception
     */
    @Override
    public int deletEemployee(Map employee) throws Exception {
        //删除人员对应的证书信息
        for (Object v : employee.values()) {
            if (v != null && v != "") {
                EmployeeCertificateVo employeeCertificateVo = new EmployeeCertificateVo();
                employeeCertificateVo.setEmployeeId(v.toString());
                List<EmployeeCertificateVo> list = employeeCertificateMapper.queryList(employeeCertificateVo);
                for (EmployeeCertificateVo li : list) {
                    if (li != null) {
                        //删除证书对应的附件信息
                        fileMapper.delByBusinessId(li.getEmployeeCertificateId());
                    }
                }
            }
        }
        //删除人员证书
        employeeCertificateMapper.updateByemployee(employee);
        return employeeMapper.updateEemployee(employee);
    }

    /**
     * 查询
     *
     * @param employee
     * @return
     * @throws Exception
     */
    @Override
    public List<EmployeeVo> queryList(Employee employee) throws Exception {
        List<EmployeeVo> list = employeeMapper.selectEmployeeList(employee);
        return list;
    }

    /**
     * 查询所有，为外部提供接口
     *
     * @param employee
     * @return
     * @throws Exception
     */
    @Override
    public List<EmployeeVo> findEmployees(Employee employee) throws Exception {
        List<EmployeeVo> list = employeeMapper.findList(employee);
        return list;

    }


    @Override
    public List<EmployeeVo> queryEmployeeByRoleDept(Map selectMap) {
        return employeeMapper.queryEmployeeByRoleDept(selectMap);
    }

    /**
     * @param list
     * @Author 卢曼成
     * @Description 批量插入
     * @Date 2017/2/8 18:04
     */
    @Override
    public int insertList(List<Employee> list) {
        return employeeMapper.insertList(list);
    }

    /**
     * @param list
     * @Author 卢曼成
     * @Description 批量修改
     * @Date 2017/2/8 17:18
     */
    @Override
    public int updateList(List<Employee> list) {
        return employeeMapper.updateList(list);
    }

    /**
     * @param list
     * @Author 卢曼成
     * @Description 批量逻辑删除
     * @Date 2017/2/8 17:18
     */
    @Override
    public int deleteList(List<Employee> list) {
        return employeeMapper.deleteList(list);
    }

    /**
     * @param orgId
     * @param sync
     * @param openOrg
     * @param openDept
     * @param keyword
     * @return
     * @throws Exception
     */
    @Override
    public List<Ztree> loadEmployeeZtree(String orgId, boolean sync, boolean openOrg, boolean openDept, String
            keyword) throws Exception {
        List<Ztree> ztreeList = new ArrayList<>();


        //没有搜索条件
        if (StringUtils.isEmpty(keyword)) {
            //初始化加载组织部门树：同时挂人员
            if (sync) {
                if (StringUtils.isNotEmpty(orgId)) {
                    //查询当前组织
                    Organization organization = organizationService.findOrgById(orgId);
                    //查询当前组织的所有儿子组织：去掉管线pipeline和井口well，这个种组织下不能挂人
                    List<Organization> orgList = organizationService.queryNodeWithoutPipelineWellByOrgId(orgId);
                    //当前组织和儿子组织：加入人员树
                    orgList.add(organization);
                    List<Ztree> orgZtreeList = organizationService.setZtree(orgList);
                    //重新设置isParent
                    for (Ztree orgZt : orgZtreeList) {
                        setOrgZtreeIsParent(orgZt, orgZt.getId());
                    }
                    ztreeList.addAll(orgZtreeList);

                    //当前组织下的人员加入人员树
                    Employee employee = new Employee();
                    employee.setOrgId(orgId);
                    List<Employee> orgEmployees = employeeMapper.selectListEmploye(employee);
                    //组织下面挂的人员：只有组织ID，不能有部门ID
                    if (orgEmployees != null) {
                        for (Employee emp : orgEmployees) {
                            if (!StringUtils.isEmpty(emp.getOrgId()) && StringUtils.isEmpty(emp.getDepId())) {
                                Ztree ztree = new Ztree();
                                ztree.setId(emp.getEmployeeId());
                                ztree.setName(emp.getName());
                                ztree.setIconSkin(TreeIconSkinEnum.ICON_PEOPLE.getDesc());
                                ztree.setOpen(true);
                                ztree.setpId(emp.getOrgId());
                                ztreeList.add(ztree);
                            }
                        }
                    }

                    //查询当前组织下的部门
                    List<Ztree> depZtrelList = departmentService.getDeptZtreeByOrgId(orgId);
                    if (depZtrelList != null) {
                        for (Ztree depZt : depZtrelList) {
                            //组织下的部门加入人员树
                            setDepZtreeIsParent(depZt, depZt.getId());
                            ztreeList.add(depZt);
                        }
                    }
                }
                //异步加载后代组织和部门及其下面挂的人员
            } else {
                if (!StringUtils.isEmpty(orgId)) {
                    //根据组织机构Id , 加载出组织机构中的人员信息
                    Employee employee = new Employee();

                    if (openOrg) {
                        //查询当前组织的所有儿子组织：排除管线和井口
                        List<Organization> orgList = organizationService.queryNodeWithoutPipelineWellByOrgId(orgId);
                        List<Ztree> orgZtreeList = organizationService.setZtree(orgList);
                        //重新设置isParent
                        for (Ztree orgZt : orgZtreeList) {
                            setOrgZtreeIsParent(orgZt, orgZt.getId());
                        }
                        ztreeList.addAll(orgZtreeList);

                        //查询当前组织下的儿子部门
                        List<Ztree> depZtreelList = departmentService.getDeptZtreeByOrgId(orgId);
                        if (depZtreelList != null) {
                            for (Ztree depZt : depZtreelList) {
                                //组织下的部门加入人员树
                                setDepZtreeIsParent(depZt, depZt.getId());
                                ztreeList.add(depZt);
                            }
                        }

                        //查询当前组织下人员
                        employee.setOrgId(orgId);
                        List<Employee> orgEmployees = employeeMapper.selectListEmploye(employee);
                        //组织下面挂的人员：只有组织ID，不能有部门ID
                        if (orgEmployees != null) {
                            for (Employee emp : orgEmployees) {
                                if (!StringUtils.isEmpty(emp.getOrgId()) && StringUtils.isEmpty(emp.getDepId())) {
                                    Ztree ztree = new Ztree();
                                    ztree.setId(emp.getEmployeeId());
                                    ztree.setName(emp.getName());
                                    ztree.setIconSkin(TreeIconSkinEnum.ICON_PEOPLE.getDesc());
                                    ztree.setOpen(true);
                                    ztree.setpId(emp.getOrgId());
                                    ztreeList.add(ztree);
                                }
                            }
                        }
                    }

                    if (openDept) {
                        //查询当前部门下的儿子部门
                        List<Ztree> depZtrelList = departmentService.queryDeptTreeByPDId(orgId);
                        if (depZtrelList != null) {
                            for (Ztree depZt : depZtrelList) {
                                //部门下的部门加入人员树
                                setDepZtreeIsParent(depZt, depZt.getId());
                                ztreeList.add(depZt);
                            }
                        }

                        //查询当前部门下的人员
                        employee.setDepId(orgId);
                        List<Employee> deptEmployees = employeeMapper.selectListEmploye(employee);
                        //部门下挂的人员：既有组织ID，又有部门ID
                        if (deptEmployees != null) {
                            for (Employee emp : deptEmployees) {
                                if (!StringUtils.isEmpty(emp.getOrgId()) && !StringUtils.isEmpty(emp.getDepId())) {
                                    Ztree ztree = new Ztree();
                                    ztree.setId(emp.getEmployeeId());
                                    ztree.setName(emp.getName());
                                    ztree.setIconSkin(TreeIconSkinEnum.ICON_PEOPLE.getDesc());
                                    ztree.setOpen(true);
                                    ztree.setpId(emp.getDepId());
                                    ztreeList.add(ztree);
                                }

                            }
                        }
                    }
                }
            }
            //有搜索条件
        } else {
            //初始化加载组织部门树：同时挂人员
            if (sync) {
                List<Ztree> totalZtreeList = this.getEmployeeMixedZtreeByOrgId(orgId);

                outZtreeService.removeDuplicate(totalZtreeList);

                if (totalZtreeList != null && totalZtreeList.size() > 0) {
                    //查询包含搜索字符的节点：并加入结果树
                    List<Ztree> targetNodeList = new ArrayList<>();
                    for (Ztree ztree : totalZtreeList) {
                        if (ztree.getName() != null) {
                            if (ztree.getName().toLowerCase().contains(keyword.toLowerCase())) {
                                targetNodeList.add(ztree);
                            }
                        }
                    }
                    ztreeList.addAll(targetNodeList);

                    //查询包含搜索字符的节点的祖先节点：并加入结果树
                    for (Ztree ztree : targetNodeList) {
                        List tempZtreeList = new ArrayList<>();
                        //递归查找祖先节点：不包括自身
                        outZtreeService.getAncestorNodeList(ztree, totalZtreeList, tempZtreeList);
                        ztreeList.addAll(tempZtreeList);
                    }

                    //必须去除：因为不同的目标节点可以有共通的父节点
                    outZtreeService.removeDuplicate(ztreeList);
                }
                //异步加载后代组织和部门及其下面挂的人员
            } else {
                if (!StringUtils.isEmpty(orgId)) {
                    //根据组织机构Id , 加载出组织机构中的人员信息
                    Employee employee = new Employee();

                    if (openOrg) {
                        //查询当前组织的所有儿子组织
                        List<Organization> orgList = organizationService.queryNodeWithoutPipelineWellByOrgId(orgId);
                        List<Ztree> orgZtreeList = organizationService.setZtree(orgList);
                        //重新设置isParent
                        for (Ztree orgZt : orgZtreeList) {
                            setOrgZtreeIsParent(orgZt, orgZt.getId());
                        }
                        ztreeList.addAll(orgZtreeList);

                        //查询当前组织下的儿子部门
                        List<Ztree> depZtreelList = departmentService.getDeptZtreeByOrgId(orgId);
                        if (depZtreelList != null) {
                            for (Ztree depZt : depZtreelList) {
                                //组织下的部门加入人员树
                                setDepZtreeIsParent(depZt, depZt.getId());
                                ztreeList.add(depZt);
                            }
                        }

                        //查询当前组织下人员
                        employee.setOrgId(orgId);
                        List<Employee> orgEmployees = employeeMapper.selectListEmploye(employee);
                        //组织下面挂的人员：只有组织ID，不能有部门ID
                        if (orgEmployees != null) {
                            for (Employee emp : orgEmployees) {
                                if (!StringUtils.isEmpty(emp.getOrgId()) && StringUtils.isEmpty(emp.getDepId())) {
                                    Ztree ztree = new Ztree();
                                    ztree.setId(emp.getEmployeeId());
                                    ztree.setName(emp.getName());
                                    ztree.setIconSkin(TreeIconSkinEnum.ICON_PEOPLE.getDesc());
                                    ztree.setOpen(true);
                                    ztree.setpId(emp.getOrgId());
                                    ztreeList.add(ztree);
                                }
                            }
                        }
                    }

                    if (openDept) {
                        //查询当前部门下的儿子部门
                        List<Ztree> depZtrelList = departmentService.queryDeptTreeByPDId(orgId);
                        if (depZtrelList != null) {
                            for (Ztree depZt : depZtrelList) {
                                //部门下的部门加入人员树
                                setDepZtreeIsParent(depZt, depZt.getId());
                                ztreeList.add(depZt);
                            }
                        }

                        //查询当前部门下的人员
                        employee.setDepId(orgId);
                        List<Employee> deptEmployees = employeeMapper.selectListEmploye(employee);
                        //部门下挂的人员：既有组织ID，又有部门ID
                        if (deptEmployees != null) {
                            for (Employee emp : deptEmployees) {
                                if (!StringUtils.isEmpty(emp.getOrgId()) && !StringUtils.isEmpty(emp.getDepId())) {
                                    Ztree ztree = new Ztree();
                                    ztree.setId(emp.getEmployeeId());
                                    ztree.setName(emp.getName());
                                    ztree.setIconSkin(TreeIconSkinEnum.ICON_PEOPLE.getDesc());
                                    ztree.setOpen(true);
                                    ztree.setpId(emp.getDepId());
                                    ztreeList.add(ztree);
                                }

                            }
                        }
                    }
                }
            }
        }

        return ztreeList;
    }

    /**
     * 获取指定组织下的所有后代组织、后代部门、后代人员的混合树
     *
     * @param orgId
     * @return
     */
    public List<Ztree> getEmployeeMixedZtreeByOrgId(String orgId) throws Exception {
        List<Ztree> ztreeList = new ArrayList<>();
        if (StringUtils.isNotEmpty(orgId)) {
            //查询当前组织
            Organization organization = organizationService.findOrgById(orgId);
            //当前登录人的组织下的人员加入人员树：包括当前组织的后代部门的人员
            Employee employee = new Employee();
            employee.setOrgId(orgId);
            List<Employee> orgEmployees = employeeMapper.selectListEmploye(employee);
            //组织下面挂的后代人员：有可能挂在组织下，也可能挂在组织的部门下
            if (orgEmployees != null) {
                for (Employee emp : orgEmployees) {
                    Ztree ztree = new Ztree();
                    ztree.setId(emp.getEmployeeId());
                    ztree.setName(emp.getName());
                    ztree.setIconSkin(TreeIconSkinEnum.ICON_PEOPLE.getDesc());
                    ztree.setOpen(true);
                    if (StringUtils.isNotEmpty(emp.getOrgId()) && StringUtils.isEmpty(emp.getDepId())) {
                        ztree.setpId(emp.getOrgId());
                    } else if (StringUtils.isNotEmpty(emp.getOrgId()) && StringUtils.isNotEmpty(emp.getDepId())) {
                        ztree.setpId(emp.getDepId());
                    }

                    ztreeList.add(ztree);
                }
            }

            //树查询自身及后代节点：向下遍历
            List<Organization> orgList = organizationService.selectDownByTreeWithoutPipelineWell(orgId);
            List<Ztree> orgZtreeList = organizationService.setZtree(orgList);
            //重新设置isParent
            for (Ztree orgZt : orgZtreeList) {
                setOrgZtreeIsParent(orgZt, orgZt.getId());
            }
            ztreeList.addAll(orgZtreeList);

            for (Organization org : orgList) {
                //所有组织下的后代部门加入人员树
                List<Ztree> depZtreelList = departmentService.getDeptZtreeByOrgId(org.getOrgId());
                if (depZtreelList != null) {
                    for (Ztree depZt : depZtreelList) {
                        //组织下的部门加入人员树
                        setDepZtreeIsParent(depZt, depZt.getId());
                        ztreeList.add(depZt);
                    }
                }

                //当前组织下的人员加入人员树：包括当前组织的后代部门的人员
                employee.setOrgId(org.getOrgId());
                orgEmployees = employeeMapper.selectListEmploye(employee);
                //组织下面挂的人员：只有组织ID，不能有部门ID
                if (orgEmployees != null) {
                    for (Employee emp : orgEmployees) {
                        Ztree ztree = new Ztree();
                        ztree.setId(emp.getEmployeeId());
                        ztree.setName(emp.getName());
                        ztree.setIconSkin(TreeIconSkinEnum.ICON_PEOPLE.getDesc());
                        ztree.setOpen(true);
                        if (StringUtils.isNotEmpty(emp.getOrgId()) && StringUtils.isEmpty(emp.getDepId())) {
                            ztree.setpId(emp.getOrgId());
                        } else if (StringUtils.isNotEmpty(emp.getOrgId()) && StringUtils.isNotEmpty(emp.getDepId())) {
                            ztree.setpId(emp.getDepId());
                        }

                        ztreeList.add(ztree);
                    }
                }

            }

            return ztreeList;
        } else {
            return null;
        }
    }

    /**
     * 人员混合树的设置组织的ztree的isParent
     *
     * @param ztree
     * @param orgId
     * @throws Exception
     */

    public void setOrgZtreeIsParent(Ztree ztree, String orgId) throws Exception {
        //查询当前组织的所有儿子组织
        List<Organization> orgList = organizationService.queryNodeWithoutPipelineWellByOrgId(orgId);
        //查询当前组织下的部门
        List<Ztree> depZtreelList = departmentService.getDeptZtreeByOrgId(orgId);
        //查询当前组织下人员
        Employee employee = new Employee();
        employee.setOrgId(orgId);
        List<Employee> orgEmployees = employeeMapper.selectListEmploye(employee);
        if ((orgList != null && orgList.size() > 0) || (depZtreelList != null && depZtreelList.size() > 0) || (orgEmployees != null && orgEmployees.size() > 0)) {
            ztree.setIsParent(true);
        } else {
            ztree.setIsParent(false);
        }
    }

    /**
     * @param ztree
     * @param depId
     * @throws Exception
     */
    @Override
    public void setDepZtreeIsParent(Ztree ztree, String depId) throws Exception {
        List<DepartmentVo> sonDepList = departmentMapper.selectByPDId(depId);
        //查询当前部门下的人员
        Employee employee = new Employee();
        employee.setDepId(depId);
        List<Employee> deptEmployees = employeeMapper.selectListEmploye(employee);

        if ((sonDepList != null && sonDepList.size() > 0) || (deptEmployees != null && deptEmployees.size() > 0)) {
            ztree.setIsParent(true);
        } else {
            ztree.setIsParent(false);
        }
    }


    /**
     * @param orgId               组织机构Id
     * @param isLoadOrg           是否加载组织
     * @param isLoadDept          是否加载部门
     * @param isLoadOrgEmployee   加载机构下面的人
     * @param isALoadDeptEmployee 加载部门下的人
     * @param maxLevel            显示组织的最大层级
     * @param lessLevel           显示组织的最小层级
     * @param keyword             搜索值
     */
    @Override
    public List<Ztree> loadEmployeeZtree(String orgId, boolean isLoadOrg, boolean isLoadDept, boolean isLoadOrgEmployee, boolean isALoadDeptEmployee, String maxLevel, String lessLevel, String keyword) throws Exception {
        // 组织机构非空判断问题！
        return null;
    }

    /**
     * @Author 卢曼成
     * @Description 根据org查询该节点人员
     * @Date 2017/3/11 17:01
     */
    @Override
    public List<Ztree> loadEmployeeZtree(String orgId) throws Exception {
        List<Ztree> list = new ArrayList<Ztree>();
        if (orgId != null) {
            Organization param = organizationService.selectOrgByOrgId(orgId);
            Ztree ztree = new Ztree();
            if (param != null) {
                ztree.setId(param.getOrgId());
                ztree.setName(param.getOrgName());
                ztree.setIconSkin(TreeIconSkinEnum.ICON_OA.getDesc());
            }
            Employee employee = new Employee();
            employee.setOrgId(orgId);
            List<Employee> employeeList = employeeMapper.selectListEmploye(employee);
            if (employeeList != null) {
                List<TeamInfo> tiList = teamInfoService.selectTeamInfos();
                List<TeamMembers> tmList = jsmTeamMembersService.selectByParamList(null);
                ztree.setOpen(true);
                list.add(ztree);
                for (Employee emp : employeeList) {
                    if (isEmployeeId(tiList, tmList, emp.getEmployeeId())) {
                        continue;
                    }
                    ztree = new Ztree();
                    ztree.setId(emp.getEmployeeId());
                    ztree.setName(emp.getName());
                    ztree.setIconSkin(TreeIconSkinEnum.ICON_PEOPLE.getDesc());
                    ztree.setOpen(true);
                    ztree.setpId(emp.getOrgId());
                    list.add(ztree);
                }
            } else {
                list.add(ztree);
            }
        }
        return list;
    }

    /**
     * 判断负责是否存在
     *
     * @param tiList
     * @param employeeId
     * @return
     */
    private boolean isEmployeeId(List<TeamInfo> tiList, List<TeamMembers> tmList, String employeeId) {
        if (tiList != null && tiList.size() > 0) {
            Iterator<TeamInfo> it = tiList.iterator();
            while (it.hasNext()) {
                TeamInfo ti = it.next();
                if (employeeId.equals(ti.getEmployeeId())) {
                    return true;
                }
            }
        }
        if (tmList != null && tmList.size() > 0) {
            Iterator<TeamMembers> it = tmList.iterator();
            while (it.hasNext()) {
                TeamMembers ti = it.next();
                if (employeeId.equals(ti.getEmployeeId())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * @param employeeId
     * @return Employee
     * @Author 卢曼成
     * @Description 根据ID查询
     * @CreateDateTime 2017/3/15 14:53
     **/
    public Employee queryByKeyId(String employeeId) {
        return employeeMapper.queryByKeyId(employeeId);
    }

    /**
     * @param list
     * @return List<String>
     * @Author 卢曼成
     * @Description 根据ID查询数据是否存在
     */
    @Override
    public List<String> selectByListId(List<Employee> list) {
        return employeeMapper.selectByListId(list);
    }

    /**
     * @param list
     * @return List<String>
     * @Author 卢曼成
     * @Description 根据postId获取关联的用户数量
     */
    @Override
    public int selectByPostCount(List<String> list) {
        return employeeMapper.selectByPostCount(list);
    }

    /**
     * @param employee 根据条件查询 人员信息 { 主要用于组织查询人 和 部门查询人信息 }
     */
    @Override
    public List<Employee> selectListEmploye(Employee employee) {
        return employeeMapper.selectListEmploye(employee);
    }

    /**
     * @param employeeId
     * @param email
     * @return boolean
     * @Author 卢曼成
     * @Description 验证邮箱是否重复
     */
    @Override
    public boolean isExisEmail(String employeeId, String email) {
        Employee employee = new Employee();
        employee.setEmployeeId(employeeId);
        employee.setEmail(email);
        int num = employeeMapper.isExis(employee);
        return num > 0 ? false : true;
    }

    /**
     * @param employeeId
     * @param loginId
     * @return boolean
     * @Author 卢曼成
     * @Description 验证用户名是否重复
     */
    @Override
    public boolean isExisLogId(String employeeId, String loginId) {
        Employee employee = new Employee();
        employee.setEmployeeId(employeeId);
        employee.setLoginId(loginId);
        int num = employeeMapper.isExis(employee);
        return num > 0 ? false : true;
    }

}
